<template>
  <div>
    <div id="play" class="page">
      <div class="content" style="margin-top:20px;">
        <div id="list" >
          <el-scrollbar>
            <div style="margin-bottom: 20px;">
              <p v-for="(item,index) in list" :key="index" :style="{color: index == currentIndex ? 'red' : 'black'}"
                  @click="playMusic(list[index]);currentIndex = index;">

                <i class="el-icon-caret-right" v-if="index == currentIndex"></i>
                {{index + 1}}、{{item.singName}} - {{item.singerName}}
              </p>
            </div>
          </el-scrollbar>
        </div>
        <div id="show">
          <p style="font-size:30px;margin-bottom: 10px;">{{current.musicName}}</p>
          <p>
            <span style="margin-right:40px;">专辑：《{{current.album}}》</span>
            <span style="float:right;margin-right:20px;">歌手：{{current.singer}}</span>
          </p>
          <div id="lyrics">
            <el-scrollbar ref="scroll">
              <p v-if="current.lyric != '' " class="lyricText" v-for="(lyric,ind) in current.lyric" :key="ind"
                :id="current.lyricId[ind]">
                  {{lyric}}
              </p>
              <h3 v-else>暂无歌词</h3>
            </el-scrollbar>
          </div>
        </div>
      </div>
    </div>
    <audio :src="'https://music.163.com/song/media/outer/url?id=' + current.url + '.mp3'" hidden></audio>
    <div id="progress">
        <span class="musicButton" @click="next('previous')">
          <i class="el-icon-back"></i>
        </span>
        <span class="musicButton" @click="startPlay()">
          <i class="el-icon-caret-right" v-if="!isPlay"></i>
          <span v-else>||</span>
        </span>
        <span class="musicButton" @click="next('next')">
          <i class="el-icon-right"></i>
        </span>
        <span>
            <span id="name">{{current.musicName}} - {{current.singer}}</span>
            <div class="content">
                <div><el-progress :percentage="progress" :format="format"></el-progress></div>
                <div><span>{{currentTime}}/{{totalTime}}</span></div>
            </div>
        </span>
    </div>
  </div>
</template>

<script>
import storageUtil from '../../utils/StorageUtil';

export default {
  name: "play",
  data(){
    return{
        list:[],
        current:{
            musicName:'',
            singer:'',
            album:'',
            url:'',
            lyric:[],
            lyricId:[],
            time:0,
            index:0,
        },
        currentIndex:0,
        isPlay:false,
        progress:0,
        totalTime:'',
        currentTime:'',
        interval:{},
    }
  },
  methods:{
      format(percentage) { return ""; },
      playMusic(item){
          if(this.isPlay == false) this.isPlay = true;
          this.current.musicName = item.singName;
          this.current.url = item.singId;
          this.current.singer = item.singerName;
          this.$get("https://autumnfish.cn/search?type=1&limit=1&keywords="+item.singerName + " " + item.singName).then(result=>{
              this.current.time = result.result.songs[0].duration;
              this.current.album = result.result.songs[0].album.name;
              this.showTime();
          })

          this.$get("https://autumnfish.cn/lyric?id=" + item.singId).then(result => {
              console.log(result);
              this.parseLyric(result.lrc.lyric);
          });
          this.startPlay();
      },
      parseLyric(lyric){
          this.current.lyric = [];
          let arrays = lyric.split('\n');
          for(let i = 0, length = arrays.length; i < length; i++){
              this.current.lyric.push(arrays[i].substring(arrays[i].indexOf(']') + 1));
              let time = arrays[i].substring(arrays[i].indexOf('[') + 1, arrays[i].indexOf(']')).split(':');
              let a = (parseFloat(time[0]) * 60 + parseFloat(time[1].substring(0,time[1].indexOf('.')))) * 1000;
              this.current.lyricId.push(a);
          }
      },
      startPlay(){
          let audio = this.$('audio')[0];
          this.isPlay = !this.isPlay;
          if(this.isPlay){
            audio.play();
          }else{
            audio.pause();
          }
      },
      next(name){
          if(name == 'next'){
              this.currentIndex++;
              if(this.currentIndex >= this.list.length){
                this.currentIndex = 0;
              }
          }else{
              this.currentIndex--;
              if(this.currentIndex < 0){
                this.currentIndex = this.list.length - 1;
              }
          }
          this.isPlay = false;
          this.playMusic(this.list[this.currentIndex]);
          this.startPlay();
          clearInterval(this.interval);
      },
      showTime(){
        let data = new Date(this.current.time);
        this.totalTime = data.getMinutes() + ":" + (data.getSeconds() >= 10 ? data.getSeconds() : '0' + data.getSeconds());
        let front = 0;
        this.interval = setInterval(() => {
            let audio = this.$('audio')[0];
            this.progress = audio.currentTime / audio.duration * 100;
            let date1 = new Date(audio.currentTime * 1000);
            this.currentTime = date1.getMinutes() + ':' + (date1.getSeconds() >= 10 ? date1.getSeconds() : '0' + date1.getSeconds());
            front = (date1.getMinutes() * 60 + date1.getSeconds()) * 1000;
            let flag = 1;
            for(let i = 0, length = this.current.lyricId.length; i < length; i++){
               if(front == this.current.lyricId[i]){
                 if(i < 10){
                   this.$refs['scroll'].wrap.scrollTop = audio.currentTime / audio.duration * 100 * i;
                 }else{
                   this.$refs['scroll'].wrap.scrollTop = audio.currentTime / audio.duration * 50 * i;
                 }
                 // this.$refs['scroll'].wrap.scrollTop = audio.currentTime / audio.duration * 400;
                 flag = 0; break;
               }
            }
            if(flag == 0)  this.$('.el-scrollbar__view>p').css({'color':'black'});
            this.$('#' + front).css({'color':'red'});

            if(this.currentTime == this.totalTime){
                clearInterval(this.interval);
                this.progress = 0;
                this.isPlay = false;
            }
        },1000);
      }
  },
  created() {
      this.list = JSON.parse(storageUtil.local.getItem("playList"));
      this.playMusic(this.list[0]);
  },
  beforeDestroy() {
    clearInterval(this.interval);
  }
}
</script>

<style>
  @import "../../static/play.css";
</style>
